/**
 * title: 写周报
 * Routes:
 *   - ./src/routes/PrivateRouter.js
 * authority: ["admin","user"]
 */
import React, { Component } from 'react'
import {Form,Input,Select,Button, Message} from 'antd';
import { Content } from '@/components/Layout';
import E from 'wangeditor';
import { connect } from 'dva';
import router from 'umi/router';
// import { dispatch } from 'rxjs/internal/observable/pairs';

class $id$ extends Component {
    constructor(props){
        super(props);
        this.id = props.match.params.id;
        this.state = {
            editorContent: null,
            editorCheck: true,
        }

    }
    componentDidMount(){
        if(this.id){
            //编辑页面
            this.getDatas().then(()=>{
                // console.log(this.props.info)
                const {content} = this.props.info;
                this.setState({
                    editorContent: content,
                })
                this.initEditor();
            });
        }else{
            this.initEditor();
        }
        this.getAllUsers();
    }
    getAllUsers(){
        this.props.dispatch({
            type: 'reports/getAllUsers',
        }).then(res => {
            this.renderUsers();
        })
    }
    getDatas() {
        return this.props.dispatch({
            type: 'reports/fetchInfo',
            payload: this.id,
        })
    }
    renderUsers(){
        const {allUsersList} = this.props;
        // console.log(allUsersList)
        return (
            <Select placeholder="请选择接收人" >
                {allUsersList.map(({username,nickname},index) => [
                    <Select.Option value={username} key={index}>
                        {nickname}
                    </Select.Option>
                ])}
            </Select>
        )
    }
    initEditor(){
        const editor = new E(this.refs.editorRef);
        editor.customConfig.onchange = html => {
            console.log(html)
            let editorCheck = true;
            if (!html || html ==='<p><br></p>'){
                editorCheck=false;
            }
            this.setState({
                editorContent: html,
                editorCheck: editorCheck
            })
        }
        editor.create();
    }
    //提交周报
    handleOk = () => {
        let { editorCheck, editorContent } = this.state;
        //表单校验
        this.props.form.validateFields((err, value) => {
            if(!err){
                //校验编辑器
                if (editorCheck && editorContent){
                    //发起请求
                    // console.log(editorContent,value);
                    this.props.dispatch({
                        type: this.id? 'reports/update' :'reports/add',
                        payload: { ...value, content: editorContent, id: this.id,},
                    }).then(res => {
                        console.log(res)
                        if (res && res.state === 'success') {
                            Message.success(res.msg || "提交周报成功");
                            router.push('/reports')
                        } else if (res && res.msg){
                            Message.success(res.msg);
                            router.push('/reports')
                        } else{
                            Message.success(res.msg || "提交周报失败");
                        }
                    }).catch(err=>console.log(err))
                } else {
                    this.setState({
                        editorCheck: false,
                    });
                }
            }
        })
    }
    render() {
        const {
            getFieldDecorator
        } = this.props.form;
        const { editorCheck } = this.state;
        const { title, receiverName, content } = this.props.info;
        return (
            <Content>
                <Form>
                    <Form.Item label="标题">
                        {
                            getFieldDecorator('title', {
                                rules: [{
                                    required: true,
                                    message: '标题不能为空',
                                },],
                                initialValue: title,
                            })(
                                <Input autoComplete='off' placeholder="请输入周报标题" />
                            )}
                    </Form.Item>
                    <Form.Item label="接收人">
                        {
                            getFieldDecorator('username', {
                                rules: [{
                                    required: true,
                                    message: '接收人不能为空',
                                },],
                                initialValue: receiverName,
                            })(
                                this.renderUsers() 
                            )}
                    </Form.Item>
                    <Form.Item label="内容" required>
                        <div ref="editorRef" dangerouslySetInnerHTML={{ __html: content}} style={!editorCheck ? {border: '1px solid red'} : {border: '1px solid #eee' }}/>
                        {!editorCheck&&<p style={{color: 'red'}}>内容不能为空</p>}
                    </Form.Item>
                    <Form.Item className="action">
                        <Button>取消</Button>
                        <Button onClick={this.handleOk} type='primary'>提交</Button>
                    </Form.Item>
                </Form>
            </Content>
        )
    }
}
export default connect(({reports})=>({...reports}))(Form.create()($id$));